package dao;

import bancoDeDados.Conexao;
import static bancoDeDados.Conexao.getConnection;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;

/**
 *
 * @author WELISSON
 */
public class GenericDAO {

    private Connection conn;

    public GenericDAO() {
        this.conn = Conexao.getConnection();
    }

    public Connection getConn() {
        return conn;
    }

    
    
    public void save(String insertSql, Object... parametros) throws SQLException {
        PreparedStatement pstmt
                = getConnection().prepareStatement(insertSql);

        for (int i = 0; i < parametros.length; i++) {
            pstmt.setObject(i + 1, parametros[i]);
        }
        
        pstmt.execute();
        pstmt.close();
    }

    public int saveReturnId(String insertSql, Object... parametros)  {
        int id = 0;
        PreparedStatement pstmt;
        try {
            pstmt = getConnection().prepareStatement(insertSql, Statement.RETURN_GENERATED_KEYS);
            for (int i = 0; i < parametros.length; i++) {
                pstmt.setObject(i + 1, parametros[i]);
            }

            pstmt.executeUpdate();
            ResultSet rs = pstmt.getGeneratedKeys();
            while (rs.next()) {
                id = rs.getInt(1);
            }
            pstmt.close();
        } catch (SQLException ex) {
            System.out.println(ex);
            return -1;
        }
        
        return id;
    }

    public void update(String updateSql, Object id, Object... parametros) throws SQLException {
        PreparedStatement pstmt
                = getConnection().prepareStatement(updateSql);

        for (int i = 0; i < parametros.length; i++) {
            pstmt.setObject(i + 1, parametros[i]);
        }
        pstmt.setObject(parametros.length + 1, id);
        pstmt.execute();
        pstmt.close();
    }

    public void delete(String deleteSql, Object... parametros) throws SQLException {
        PreparedStatement pstmt
                = getConnection().prepareStatement(deleteSql);

        for (int i = 0; i < parametros.length; i++) {
            pstmt.setObject(i + 1, parametros[i]);
        }

        pstmt.execute();
        pstmt.close();
    }

}
